<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-left">
        <h2>欢迎登录</h2>
        <p>聊天系统</p>
        <img
          src="https://images.unsplash.com/photo-1551650975-87deedd944c3?ixlib=rb-1.2.1&auto=format&fit=crop&w=300&h=300&q=80"
          alt="注册插图"
          class="login-image"
        />
      </div>
      <div class="login-right">
        <div class="login-form">
          <h3 class="title">账号登录</h3>

          <el-tabs v-model="activeName" stretch>
            <el-tab-pane label="账号密码" name="account">
              <el-form
                ref="loginForm"
                :model="loginForm"
                :rules="loginRules"
                class="login-form"
                auto-complete="on"
                label-position="left"
              >
                <el-form-item prop="account">
                  <el-input
                    ref="account"
                    v-model="loginForm.account"
                    placeholder="用户名/邮箱/手机号"
                    name="account"
                    type="text"
                    tabindex="1"
                    auto-complete="on"
                    prefix-icon="el-icon-user"
                  />
                </el-form-item>

                <el-form-item prop="password">
                  <el-input
                    :key="passwordType"
                    ref="password"
                    v-model="loginForm.password"
                    :type="passwordType"
                    placeholder="密码"
                    name="password"
                    tabindex="2"
                    auto-complete="on"
                    prefix-icon="el-icon-lock"
                    @keyup.enter.native="handleLogin"
                  />
                  <span class="show-pwd" @click="showPwd">
                    <svg-icon
                      :icon-class="
                        passwordType === 'password' ? 'eye' : 'eye-open'
                      "
                    />
                  </span>
                </el-form-item>

                <el-form-item>
                  <el-checkbox v-model="loginForm.rememberMe"
                    >记住我</el-checkbox
                  >
                  <el-link type="primary" :underline="false" class="forget-pwd"
                    >忘记密码?</el-link
                  >
                </el-form-item>

                <el-button
                  :loading="loading"
                  type="primary"
                  style="width: 100%; margin-bottom: 20px"
                  @click.native.prevent="handleLogin"
                >
                  登录
                </el-button>
              </el-form>
            </el-tab-pane>

            <el-tab-pane label="手机验证码" name="mobile">
              <el-form
                ref="mobileForm"
                :model="mobileForm"
                :rules="mobileRules"
                class="login-form"
                auto-complete="on"
                label-position="left"
              >
                <el-form-item prop="mobile">
                  <el-input
                    ref="mobile"
                    v-model="mobileForm.mobile"
                    placeholder="手机号码"
                    name="mobile"
                    type="text"
                    tabindex="1"
                    auto-complete="on"
                    prefix-icon="el-icon-mobile-phone"
                  />
                </el-form-item>

                <el-form-item prop="code">
                  <el-input
                    v-model="mobileForm.code"
                    placeholder="验证码"
                    name="code"
                    type="text"
                    tabindex="2"
                    auto-complete="on"
                    prefix-icon="el-icon-message"
                    style="width: 65%"
                  />
                  <el-button
                    :disabled="codeDisabled"
                    style="width: 33%; margin-left: 2%"
                    @click.native.prevent="sendCode"
                  >
                    {{ codeText }}
                  </el-button>
                </el-form-item>

                <el-button
                  :loading="loading"
                  type="primary"
                  style="width: 100%; margin-bottom: 20px"
                  @click.native.prevent="handleMobileLogin"
                >
                  登录
                </el-button>
              </el-form>
            </el-tab-pane>
          </el-tabs>

          <div class="login-footer">
            <div class="register-link">
              还没有账号？
              <el-link type="primary" :underline="false" @click="handleRegister"
                >立即注册</el-link
              >
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "LoginPage",
  data() {
    const validateAccount = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入用户名/邮箱/手机号"))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error("密码不能少于6位"))
      } else {
        callback()
      }
    }
    const validateMobile = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入手机号码"))
      } else if (!/^1[3-9]\d{9}$/.test(value)) {
        callback(new Error("手机号码格式不正确"))
      } else {
        callback()
      }
    }
    const validateCode = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入验证码"))
      } else if (!/^\d{6}$/.test(value)) {
        callback(new Error("验证码为6位数字"))
      } else {
        callback()
      }
    }
    return {
      activeName: "account",
      loginForm: {
        acc: "",
        password: "",
        rememberMe: false
      },
      mobileForm: {
        mobile: "",
        code: ""
      },
      loginRules: {
        account: [
          { required: true, trigger: "blur", validator: validateAccount }
        ],
        password: [
          { required: true, trigger: "blur", validator: validatePassword }
        ]
      },
      mobileRules: {
        mobile: [
          { required: true, trigger: "blur", validator: validateMobile }
        ],
        code: [{ required: true, trigger: "blur", validator: validateCode }]
      },
      passwordType: "password",
      loading: false,
      codeDisabled: false,
      codeText: "获取验证码",
      countdown: 60,
      redirect: undefined
    }
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    }
  },
  methods: {
    showPwd() {
      if (this.passwordType === "password") {
        this.passwordType = ""
      } else {
        this.passwordType = "password"
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    handleLogin() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.loading = true
          this.$store
            .dispatch("login", this.loginForm)
            .then(() => {
              this.$router.push({ path: this.redirect || "/" })
              this.loading = false
            })
            .catch(() => {
              this.loading = false
            })
        } else {
          console.log("error submit!!")
          return false
        }
      })
    },
    handleMobileLogin() {
      this.$refs.mobileForm.validate((valid) => {
        if (valid) {
          this.loading = true
          // 这里替换为实际的手机验证码登录API调用
          setTimeout(() => {
            this.loading = false
            this.$message.success("手机验证码登录成功")
          }, 1500)
        } else {
          console.log("error submit!!")
          return false
        }
      })
    },
    sendCode() {
      this.$refs.mobileForm.validateField("mobile", (valid) => {
        if (!valid) {
          this.codeDisabled = true
          const timer = setInterval(() => {
            this.countdown--
            this.codeText = `${this.countdown}秒后重新获取`
            if (this.countdown <= 0) {
              clearInterval(timer)
              this.codeText = "获取验证码"
              this.countdown = 60
              this.codeDisabled = false
            }
          }, 1000)

          // 这里替换为实际的发送验证码API调用
          this.$message.success("验证码已发送")
        }
      })
    },
    handleRegister() {
      this.$router.push("/register")
    }
  }
}
</script>

<style lang="scss" scoped>
.login-container {
  min-height: 100%;
  width: 100%;
  background-color: #f0f2f5;
  background-image: url("https://gw.alipayobjects.com/zos/rmsportal/TVYTbAXWheQpRcWDaDMu.svg");
  background-repeat: no-repeat;
  background-position: center 110px;
  background-size: 100%;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;

  .login-box {
    width: 900px;
    height: 500px;
    background: #fff;
    border-radius: 10px;
    box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
    display: flex;
    overflow: hidden;

    .login-left {
      width: 40%;
      background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
      color: #fff;
      padding: 40px;
      display: flex;
      flex-direction: column;
      justify-content: center;

      h2 {
        font-size: 28px;
        margin-bottom: 10px;
      }

      p {
        font-size: 16px;
        margin-bottom: 40px;
        opacity: 0.9;
      }

      .login-image {
        width: 100%;
        margin-top: 30px;
        border-radius: 5px;
      }
    }

    .login-right {
      width: 60%;
      padding: 40px;

      .login-form {
        height: 100%;
        display: flex;
        flex-direction: column;

        .title {
          font-size: 24px;
          color: #333;
          margin-bottom: 30px;
          text-align: center;
          font-weight: 500;
        }

        ::v-deep .el-tabs__item {
          font-size: 16px;
          height: 50px;
          line-height: 50px;
        }

        ::v-deep .el-tabs__nav-wrap::after {
          height: 1px;
        }

        .forget-pwd {
          float: right;
        }

        .login-footer {
          margin-top: auto;
          text-align: center;

          .third-party {
            margin: 20px 0;

            .third-icon {
              font-size: 24px;
              color: #606266;
              margin: 0 10px;
              cursor: pointer;
              transition: color 0.3s;

              &:hover {
                color: #409eff;
              }
            }
          }

          .register-link {
            font-size: 14px;
            color: #606266;
          }
        }
      }
    }
  }
}

.show-pwd {
  position: absolute;
  right: 10px;
  top: 7px;
  font-size: 16px;
  color: #889aa4;
  cursor: pointer;
  user-select: none;
}

@media (max-width: 768px) {
  .login-container {
    .login-box {
      width: 100%;
      flex-direction: column;
      height: auto;

      .login-left,
      .login-right {
        width: 100%;
      }

      .login-left {
        padding: 20px;
        text-align: center;

        .login-image {
          display: none;
        }
      }

      .login-right {
        padding: 20px;
      }
    }
  }
}
</style>
